import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'setup',
      component: () => import('@/views/StartPage.vue'),
      meta: { title: '启动页' }
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notfound',
      component: () => import('@/views/NotFound.vue'),
      meta: { title: '404页面不存在' }
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/home/HomePage.vue'),
      meta: { isLogin: true, title: '首页' }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/LoginPage.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/regist',
      name: 'regist',
      component: () => import('@/views/regist/RegistPage.vue'),
      meta: { title: '注册' }
    }
  ]
})

router.beforeEach((to, from) => {
  console.log(to, from)
  console.log(to.meta.title)

  if (to.meta.title) document.title = to.meta.title as string

  if (to.meta.isLogin) {
    const token = localStorage.getItem('token')
    if (!token) {
      return { name: 'login' }
    }
  }
})

export default router
